package com.ruoyi.ys7Video.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.detection.controller.test;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.utils.FileTool;
import com.ruoyi.utils.MyDateUtil;
import com.ruoyi.ys7Video.domain.DeviceInfo;
import com.ruoyi.ys7Video.domain.VideoDao;
import com.ruoyi.ys7Video.domain.VideoTokenDao;
import com.ruoyi.ys7Video.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;


/**
 * 视频相关处理_controller
 *
 * @author Mr-Le
 */
@Api("视频处理类")
@Slf4j
@RestController
@RequestMapping("/video")
public class VideoController extends BaseController {

    /**
     * 获取身份令牌
     */
    @Autowired
    private TokenService tokenService;

    /**
     * 获取萤石云 key
     */
    @Value("${ys7.ys7AppKey}")
    private String ys7AppKey;

    /**
     * 获取萤石云密钥
     */
    @Value("${ys7.ys7AppSecret}")
    private String ys7AppSecret;

    /**
     * 萤石云 Token Url
     */
    @Value("${ys7.ys7tokenUrl}")
    private String ys7tokenUrl;

    /**
     * 萤石云 获取-播放地址 Url
     */
    @Value("${ys7.ys7LiveAddress}")
    private String ys7LiveAddress;

    /**
     * 萤石云 抓拍图片地址
     */
    @Value("${ys7.ys7CaptureUrl}")
    private String ys7CaptureUrl;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * service
     */
    @Autowired
    private VideoService videoService;

    /**
     * 查询视频设备列表
     *
     * @param videoDao 实体类
     * @return 列表
     */
    @ApiOperation("查询视频设备列表,同时可含deviceSerial参数查找，示例 http://localhost:8080/video/list?deviceSerial=F94404261")
    @GetMapping("/list")
    public TableDataInfo getVideoDeviceList(VideoDao videoDao) {
        startPage();
        List<VideoDao> list = videoService.selectVideoDevice(videoDao);
        return getDataTable(list);
    }

    /**
     * 根据appKey和secret获取accessToken
     * 增加token过期检测，默认token7天过期，此处设置为5天默认时间
     *
     * @return
     */
    @ApiOperation("获取YS7的accessToken")
    @PostMapping("/token")
    public AjaxResult getYs7AccessToken() {
        long currentTimeMillis = System.currentTimeMillis();
        VideoDao videoLast = videoService.selectVideoLast();
        long expireTime = 0;
        // 过期时间设置阈值，7天改为5天
        if (videoLast.getExpireTime() != null) {
            expireTime = videoLast.getExpireTime() - (48L * 3600L * 1000L);
        }
        if ((currentTimeMillis <= expireTime) && (expireTime > 0)) {
            return AjaxResult.success(videoLast);
        } else {
            /* 拼接获取token的URL */
            String getTokenUrl = ys7tokenUrl + "?appKey=" + ys7AppKey + "&appSecret=" + ys7AppSecret;
            VideoDao videoDao = null;
            try {
                ResponseEntity<String> responseEntity = Threads.postRequest(getTokenUrl);
                /* 拿到data数据 */
                JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
                String s = jsonObject.getJSONObject("data").toString();
                videoDao = JSON.parseObject(s, VideoDao.class);
                log.info(videoDao.toString());
            } catch (Exception e) {
                System.out.println(e);
            }
            if (StringUtils.isNotNull(videoDao)) {
                VideoTokenDao videoTokenDao = new VideoTokenDao(videoLast.getAccessToken(), videoDao.getAccessToken(), videoLast.getExpireTime(), videoDao.getExpireTime());
                videoService.updateToken(videoTokenDao);
                videoService.updateTokenExpireTime(videoTokenDao);
                return AjaxResult.success(videoDao);
            } else {
                return AjaxResult.error("请求Token出错！重试!");
            }
        }
    }

    /**
     * 根据序列号获取直播地址
     *
     * @param deviceSerial 序列号
     * @return 播放地址
     */
    @ApiOperation("根据设备序列号获取ys7的播放地址，即：deviceSerial")
    @PostMapping("/liveaddress")
    public AjaxResult getYs7LiveAddress(String deviceSerial) {
        // 拼接获取Address的Url, 查询数据库拿到token，仅为了拿到token
        VideoDao videoDao = videoService.selectVideoLast();
        log.info("---------->" + videoDao.toString());
//        String getLiveAddressUrl = ys7LiveAddress + "?accessToken=" + videoDao.getAccessToken() + "&deviceSerial=" + videoDao.getDeviceSerial();
        String getLiveAddressUrl = ys7LiveAddress + "?accessToken=" + videoDao.getAccessToken() + "&deviceSerial=" + deviceSerial;
        log.info(getLiveAddressUrl);
        try {
            ResponseEntity<String> responseEntity = Threads.postRequest(getLiveAddressUrl);
            /* 拿到data数据 */
            JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
            String s = jsonObject.getJSONObject("data").toString();
            log.info(s);
            videoDao = JSON.parseObject(s, VideoDao.class);
            videoDao.setDeviceSerial(deviceSerial);
            log.info(videoDao.toString());
        } catch (Exception e) {
            System.out.println(e);
        }
        if (StringUtils.isNotNull(videoDao)) {
//            videoService.updateVideoLast(videoDao);
            videoService.insertVideoUrl(videoDao);
//            videoDao = videoService.selectVideoLast();
            return AjaxResult.success(videoDao);
        } else {
            return AjaxResult.error("请求视频播放链接出错！重试!");
        }
    }

    /**
     * 根据设备序列号抓拍图片
     *
     * @param deviceSerial 设备序列号
     * @return 结果
     */
    @ApiOperation("抓拍图片接口，根据设备序列号抓拍")
    @GetMapping("/capture")
    public AjaxResult CaptureImgBySerial(String deviceSerial) {
        VideoDao videoLast = videoService.selectVideoLast();
        /* 拼接获取token的URL */
        String getTokenUrl = ys7CaptureUrl + "?accessToken=" + videoLast.getAccessToken() + "&deviceSerial=" + deviceSerial + "&channelNo=1";
        VideoDao videoDao = null;
        try {
            ResponseEntity<String> responseEntity = Threads.postRequest(getTokenUrl);
            /* 拿到data数据 */
            JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
            String s = jsonObject.getJSONObject("data").toString();
            videoDao = JSON.parseObject(s, VideoDao.class);
            log.info(videoDao.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        if (StringUtils.isNotNull(videoDao)) {
            String path = profile + File.separator + "capture" + File.separator + deviceSerial;
            String date = MyDateUtil.dateFormate(new Date(), "yyyy_MM_dd_HH_mm_ss");
            String fileNme = deviceSerial + "_" + date + ".jpg";
            // 存放结果路径
            String resultPath = null;
            VideoDao videoDaoResult = new VideoDao();
            boolean isSuccess = FileTool.downloadImageByUrl(videoDao.getPicUrl(), path, fileNme);
            if (isSuccess) {
                resultPath = "profile" + File.separator + "capture" + File.separator + deviceSerial + File.separator + fileNme;
                videoDaoResult.setDeviceSerial(deviceSerial).setPicUrl(resultPath);
                videoService.insertCaptureImg(videoDaoResult);
            }
            // 插入数据库操作

            return isSuccess ? AjaxResult.success("保存图片成功，保存至默认路径!", resultPath) : AjaxResult.error("保存图片出错！");
        } else {
            return AjaxResult.error("抓拍图片出错！");
        }
    }

    /**
     * 抓拍图片列表展示
     *
     * @param deviceSerial 设备序列号
     * @return 集合
     */
    @ApiOperation("抓拍图片列表展示，例如：http://localhost:8080/video/captureList?deviceSerial=F94404261")
    @GetMapping("/captureList")
    public TableDataInfo captureImgList(String deviceSerial) {
        startPage();
        List<VideoDao> videoDaos = videoService.selectCaptureImgList(deviceSerial);
        return getDataTable(videoDaos);
    }


    @ApiOperation("获取设备列表")
    @GetMapping("/ys7List")
    public List<DeviceInfo> ys7DevicesList() {
        return videoService.ys7DeviceList();
    }


}
